package com.ptc.otkjavaexamples.ui;

import com.ptc.otkjavaexamples.ui.pojo.DataPack;
import com.ptc.otkjavaexamples.ui.pojo.DataStorage;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class ResourceParser {
    public ResourceParser() {
    }

    private String filePath ;

    public String getFilePath() {
        return filePath;
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }

    public ResourceParser(String filePath) {
        this.filePath = filePath;
    }

    public DataPack parseFile() throws IOException {
        DataPack result = new DataPack();
        ArrayList<String> composeSequence = new ArrayList<>();
        if(filePath==null){
            throw new FileNotFoundException("没资源文件你解析个毛线");
        }

        HashMap<String, DataStorage> map = new HashMap<>();

        // 使用InputStreamReader并指定UTF-8编码
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(new FileInputStream(filePath), StandardCharsets.UTF_8)
        );
        String buffer ;
        while ((buffer = reader.readLine())!=null){
            String[] split = buffer.split("/");
            if(split.length!=4){
                throw new RuntimeException("资源文件格式错误");
            }
            String id = split[0].trim();
            String label = split[1].trim();
            String parentId = split[2].trim();
            composeSequence.add(id);

//            System.out.println(label);

            DataStorage data = new DataStorage();
            data.setLabel(label);
            data.setParentId(parentId);

            String path = split[3].trim();
            if(path.equals("undefined")){
                data.setPath(null);
            }else {
                String[] pathSplit = path.split(",");
                int []  asmPath = new int [pathSplit.length];
                for (int i = 0; i < pathSplit.length; i++) {
                    asmPath[i] = Integer.parseInt(pathSplit[i]);
                }
                data.setPath(asmPath);
            }
            map.put(id,data);
        }
        result.setMap(map);
        result.setComposeSequence(composeSequence);

        return  result;

    }
}
